package com.east.sng.controller;

import com.alibaba.excel.EasyExcel;
import com.east.sng.entity.param.StuParam;
import com.east.sng.entity.param.StuSearchParam;
import com.east.sng.entity.result.*;
import com.east.sng.service.CourseService;
import com.east.sng.service.StuService;
import com.east.sng.utils.EncryptDataUtil;
import com.east.sng.utils.ValidationUtil;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * @author east
 * @date: 2020/12/31
 * @Description:
 **/
@Controller
@RequestMapping("/stu")
public class StuController {
    @Autowired
    private StuService stuService;
    @Autowired
    private CourseService courseService;

    /**
     * 学生信息页面跳转
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequiresPermissions("stu:list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(@Valid StuSearchParam stu, @RequestParam(name = "pn", defaultValue = "1") Integer pageNum,
                       @RequestParam(name = "pSize", defaultValue = "5") Integer pageSize, Model model) {
        model.addAttribute("page", PageHelper.startPage(pageNum, pageSize));
        List<StuInfo> list = this.stuService.findStus(stu);
        //给学生监护人手机号码加密
        list.forEach((item)-> {
            String encryptPhone = EncryptDataUtil.encryptPhone(item.getStuParentPhone());
            item.setStuParentPhone(encryptPhone);
        });
        model.addAttribute("stus", list);
        model.addAttribute("courses", this.courseService.findCourseColumns());
        return "stu/list";
    }

    /**
     * 学生添加页面跳转
     * @param model
     * @return
     */
    @RequiresPermissions("stu:add")
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String toAddStu(Model model) {
        model.addAttribute("courses", this.courseService.findCourseColumns());
        return "stu/add";
    }

    /**
     * 学生信息添加
     * @param stu
     * @param br
     * @return
     */
    @RequiresPermissions("stu:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addStu(@Valid StuParam stu, BindingResult br) {
        ValidationUtil.validateData(br);
        if (stu.parseStuParentRelation()){
            this.stuService.addStu(stu);
        }
        return "success";
    }

    /**
     * 学生修改页面跳转
     * @param stuId
     * @param model
     * @return
     */
    @RequiresPermissions(value = {"stu:list","stu:add"},logical = Logical.AND)
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String toEditStu(Integer stuId, Model model) {
        StuFind stu = this.stuService.findStu(stuId);
        model.addAttribute("courses", this.courseService.findCourseColumns());
        model.addAttribute("stu", stu);
        return "stu/edit";
    }

    /**
     * 学生信息修改
     * @param stu
     * @param br
     * @return
     */
    @RequiresPermissions(value = {"stu:list","stu:add"},logical = Logical.AND)
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String editStu(@Valid StuParam stu, BindingResult br) {
        ValidationUtil.validateData(br);
        if (stu.parseStuParentRelation()){
            this.stuService.editStu(stu);
        }
        return "success";
    }

    /**
     * 学生信息删除
     * @param id
     * @return
     */
    @RequiresRoles(value = {"0","1"},logical = Logical.OR)
    @RequiresPermissions(value = {"stu:list","stu:add"},logical = Logical.AND)
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public String removeStu(Integer id) {
        return this.stuService.removeStu(id) ? "success" : "fail";
    }

    /**
     * 学生信息恢复
     * @param id
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions(value = {"stu:list","stu:add"},logical = Logical.AND)
    @RequestMapping(value = "/recover", method = RequestMethod.POST)
    @ResponseBody
    public String recoverStu(Integer id) {
        return this.stuService.recoverStu(id) ? "success" : "fail";
    }

    /**
     * 学生信息批量删除
     * @param ids
     * @return
     */
    @RequiresRoles(value = {"0","1"},logical = Logical.OR)
    @RequiresPermissions(value = {"stu:list","stu:add"},logical = Logical.AND)
    @RequestMapping(value = "/removes", method = RequestMethod.POST)
    @ResponseBody
    public String removeStus(Integer[] ids) {
        return this.stuService.batchRemoveStus(Arrays.asList(ids)) ? "success" : "fail";
    }

    /**
     * 学生信息批量恢复
     * @param ids
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions(value = {"stu:list","stu:add"},logical = Logical.AND)
    @RequestMapping(value = "/recovers", method = RequestMethod.POST)
    @ResponseBody
    public String recoverStus(Integer[] ids) {
        return this.stuService.batchRecoverStus(Arrays.asList(ids)) ? "success" : "fail";
    }

    /**
     * 根据学生姓名查询学生信息
     * @return
     */
    @RequestMapping(value = "/findStuInfo", method = RequestMethod.POST)
    @ResponseBody
    public List<StuSearchFind> findStuInfo(String stuName) {
        return this.stuService.findStuColumns(stuName);
    }

    /**
     * 查询学生课程信息
     * @return
     */
    @RequestMapping(value = "/findStuCourse", method = RequestMethod.POST)
    @ResponseBody
    public StuCourseFind findStuCourseInfo(Integer stuId) {
        return this.stuService.findStuCourseInfo(stuId);
    }

    /**
     * 导出学生信息
     * @param stuIds
     * @param response
     * @throws Exception
     */
    @RequiresPermissions("stu:list")
    @RequestMapping(value = "/exportStuInfo", method = RequestMethod.POST)
    public void exportStuInfo(Integer[] stuIds, HttpServletResponse response) throws Exception {
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 使用URLEncoder的encode来防止中文乱码
            String fileName = URLEncoder.encode("学生信息表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            outputStream = response.getOutputStream();
            EasyExcel.write(outputStream, StuInfo.class).sheet("学生信息表").doWrite(this.stuService.findStuInfo(Arrays.asList(stuIds)));
        } finally {
            try {
                //关闭流
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}